package zju.xmsx.acm.search.back;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import zju.xmsx.acm.search.back.dao.UserRepository;
import zju.xmsx.acm.search.back.dto.MessageResponse;
import zju.xmsx.acm.search.back.dto.User;

import javax.annotation.Resource;
import java.util.Map;

@RestController
public class UserController {

    @Resource
    private UserRepository userRepository;

    @PostMapping("/register")
    public MessageResponse register(@RequestBody User user) {
        if (userRepository.findByEmail(user.getEmail()) != null) {
            return new MessageResponse(false, "注册失败，该邮箱已被注册");
        }
        userRepository.save(user);
        return new MessageResponse(true, "注册成功", user.getUserName());
    }

    @PostMapping("/login")
    public MessageResponse login(@RequestBody Map<String, String> param) {
        String email = param.get("email");
        String password = param.get("password");
        User t = userRepository.findByEmail(email);
        if (t == null || !t.getPassword().equals(password)) {
            return new MessageResponse(false, "登陆失败，用户名或密码错误");
        }
        return new MessageResponse(true, "登录成功", t.getUserName());
    }

}
